﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebPortal.Models.EntityModels;
using WebPortal.Models.ViewModel;
using System.Web.Script.Serialization;

namespace WebPortal.Controllers
{
    public class BasketController : BaseController
    {
        //
        // GET: /Main

        public string Add()
        {
            bool res = false;
            try
            {
                int id = Convert.ToInt32(Request["id"]);
                Basket b = new Basket();
                b.UserID = User.UserID;
                b.GoodID = id;
                b.BasketID = 0;
                dbBasket.AddToBasket(b);
                dbBasket.SaveChanges();
                res = true;
            }
            catch (Exception e)
            {
                //
            }
            return new JavaScriptSerializer().Serialize(res);
        }

        public string Del()
        {
            try
            {
                int id = Convert.ToInt32(Request["id"]);
                var basket = (from b in dbBasket.Basket where b.GoodID == id && b.UserID == User.UserID select b).ToList();
                if (basket.Count > 0)
                {
                    dbBasket.DeleteObject(basket[0]);
                    dbBasket.SaveChanges();
                }
                return new JavaScriptSerializer().Serialize(basket.Count-1);
            }
            catch (Exception e)
            {
                //
            }
            return new JavaScriptSerializer().Serialize(false);
        }

        public ActionResult Index()
        {
            var categories = (from cat in dbCategories.Categories select cat).ToList();
            var basket = (from b in dbBasket.Basket where b.UserID == User.UserID select b.GoodID).ToList();
            var goods = (from good in dbGoods.Goods
                         where basket.Contains(good.GoodID)
                         select good).ToList();
            GoodsModelList list = GoodsModel.GetGoods(goods, categories, basket);
            return View(list);
        }

        public ActionResult Search()
        {
            GoodsModelList list = new GoodsModelList();
            try
            {
                int catID = Convert.ToInt32(Request["id"]);
                var categories = (from cat in dbCategories.Categories where cat.CategoryID == catID select cat).ToList();
                var basket = (from b in dbBasket.Basket where b.UserID == User.UserID select b.GoodID).ToList();
                var goods = (from good in dbGoods.Goods where good.CategoryID == catID && basket.Contains(good.GoodID) select good).ToList();
                list = GoodsModel.GetGoods(goods, categories, basket);
            }
            catch (Exception e)
            {
                //
            }
            return View(list);
        }
    }
}
